﻿using AutoMapper;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using RTools_NTS.Util;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using ZGL.Api.Data;
using ZGL.Api.Entity;
using ZGL.Api.Models.dto;
using ZGL.Api.Models.vo;
using ZGL.Api.Utils;

namespace ZGL.Api.Services.User
{
    public class UserService : IUserService
    {
        public DataContext DataContext { get; }
        private readonly IMapper Mapper;
        public UserService(DataContext dataContext, IMapper _mapper)
        {
            this.DataContext = dataContext;
            this.Mapper = _mapper;
        }
        public void addUser(UserAddDto user)
        {
            if (DataContext.SysUsers.Any(r => r.Username == user.Username)) {
                throw new Exception("用户名已存在");
            }
            //密码加密
            user.Password = new PasswordHasher<UserAddDto>().HashPassword(null, user.Password);
            var sysUser = Mapper.Map<SysUser>(user);
            DataContext.SysUsers.Add(sysUser);  
            DataContext.SaveChanges();
            //新增角色-用户表
            List<SysUserRoleRelation> roleUserAuth = new List<SysUserRoleRelation>();
            List<int> roleId = user.RoleId;
            foreach (int id in roleId)
            {
                SysUserRoleRelation sysRoleUserAuth = new SysUserRoleRelation();
                sysRoleUserAuth.RoleId = id;
                sysRoleUserAuth.UserId = sysUser.UserId;
                roleUserAuth.Add(sysRoleUserAuth);
            }
            DataContext.SysUserRoleRelations.AddRange(roleUserAuth);
            DataContext.SaveChanges();
            return;
        }

        public int delUser(long id)
        {
            var user = DataContext.SysUsers.Find(id);
            if (user != null)//删除角色-用户表
            {
                DataContext.SysUsers.Remove(user);
                DataContext.SysUserRoleRelations.Where(r => r.UserId == id).ExecuteDelete();
                DataContext.SaveChanges();
            }
            else
            {
                throw new Exception("无此用户");
            }
            return 1;
        }

        public SysUserDetailsVo getUser(long id)
        {
            var User = DataContext.SysUsers.Where(r=>r.UserId==id).ToList();

            var userRoles=DataContext.SysUserRoleRelations.Where(r => r.UserId == id).ToList();
            var item =from u in User
                      join j in DataContext.SysUserRoleRelations.ToList()
                      on u.UserId equals j.UserId
                      join z in DataContext.SysRoles.ToList()
                      on j.RoleId equals z.RoleId
                      select new SysUserDetailsVo
                      {
                          userRole= userRoles,
                          RoleId = j.RoleId.ToString(),
                          RoleName = z.RoleName,
                          UserId=u.UserId,
                          CorpId = u.CorpId,
                          Username = u.Username,
                          Password = u.Password,
                          Realname = u.Realname,
                          Station = u.Station,
                          Telephone = u.Telephone,
                          JobNum = u.JobNum,
                          Openid= u.Openid,
                          PhotoUrl = u.PhotoUrl,
                          CreateTime = u.CreateTime,
                          UpdateTime = u.UpdateTime,
                      };
            if (item.Count()==0) {
                throw new Exception("无此用户");
            }
            return item.FirstOrDefault();
        }

        public Dictionary<string, object> getUserList(UserDto userDto)
        {
            IQueryable<SysUser> list = null;
            int total = 0;
            Dictionary<string, object> Dictionary = new Dictionary<string, object>();

            
            if (!string.IsNullOrEmpty(userDto.Username))
            {
                //list = from s in DataContext.SysUsers where s.Username.Contains(userDto.Username) orderby s.UserId select s;
                list = DataContext.SysUsers.Where(r => r.Username.Contains(userDto.Username)).OrderBy(r => r.UserId);
            }else if(!string.IsNullOrEmpty(userDto.Telephone)) 
             {
                list = DataContext.SysUsers.Where(r => r.Telephone.Contains(userDto.Telephone)).OrderBy(r => r.UserId);
            }
            else
            {
                list = DataContext.SysUsers.OrderBy(r => r.UserId);
            }
            List<SysUser> items = new List<SysUser>();
            items = list.Skip((userDto.current - 1) * userDto.size).Take(userDto.size).ToList();
            //用户-角色
            var userList = Mapper.Map <List<SysUserVo>>(items);
            var query = from u in userList
                        join i in DataContext.SysUserRoleRelations.ToList()
                        on u.UserId equals i.UserId 
                        join z in DataContext.SysRoles.ToList()
                        on i.RoleId equals z.RoleId 
                        select new
                        {
                            RoleId= i.RoleId.ToString(),
                            RoleName=z.RoleName,
                            u.UserId,
                            u.CorpId,
                            u.Username,
                            u.Password,
                            u.Realname,
                            u.Station,
                            u.Telephone,
                            u.JobNum,
                            u.Openid,
                            u.PhotoUrl,
                            u.CreateTime,
                            u.UpdateTime,
                        };
            total = list.Count();
            Dictionary.Add("list", query);
            Dictionary.Add("total", total);
            return Dictionary;
        }
        /// <summary>
        /// /修改用户
        /// </summary>
        /// <param name="user"></param>
        public void putUser(UserPutDto user)
        {
            var sysUser = Mapper.Map<SysUser>(user);
            DataContext.SysUsers.Update(sysUser);
            var role=DataContext.SysUserRoleRelations.Where(r=>r.UserId== user.UserId);
            //查询角色跟修改角色是否相等，不同择修改，相同择证明不用修改  先删除
            if (role != null)
            {
                role.ExecuteDelete();
            }
            //再新增
            List<SysUserRoleRelation> roleUserAuth = new List<SysUserRoleRelation>();
            List<int> userId = user.userRole;
            foreach (int id in userId)
            {
                SysUserRoleRelation sysRoleUserAuth = new SysUserRoleRelation();
                sysRoleUserAuth.RoleId = id;
                sysRoleUserAuth.UserId = sysUser.UserId;
                roleUserAuth.Add(sysRoleUserAuth);
            }
            DataContext.SysUserRoleRelations.AddRange(roleUserAuth);
            DataContext.SaveChanges();
            return;
        }

        public Dictionary<string, object> login(LogonDto logonDto)
        {
            Dictionary<string, object> Dictionary = new Dictionary<string, object>();
            //UserLoignVo
            if (string.IsNullOrEmpty(logonDto.Username)|| string.IsNullOrEmpty(logonDto.Password)) {
                throw new Exception("用户名或密码不能为空");
            }
            if (!DataContext.SysUsers.Any(r => r.Username == logonDto.Username)) {
                throw new Exception("用户名不存在");
            }
            var hasher = new PasswordHasher<object>(); // 使用object作为泛型参数，如果你不需要特定用户类型。
            var stored = DataContext.SysUsers.Where(r=>r.Username== logonDto.Username).FirstOrDefault(); // 示例哈希值，从数据库获取。
            var enteredPassword = logonDto.Password; // 用户输入的密码。
            var result = hasher.VerifyHashedPassword(null, stored.Password, enteredPassword);
            if (result != PasswordVerificationResult.Success)
            {
                throw new Exception("密码验证失败！");
            }
            //获取用户信息
            var User = stored;
            #region 获取用户信息角色id及name
            var UserVo = Mapper.Map<SysUserVo>(User);
            var roleList = from u in DataContext.SysUserRoleRelations
                      where u.UserId == User.UserId
                      join i in DataContext.SysRoles on u.RoleId equals i.RoleId
                     select i;
            UserVo.RoleName = string.Join(", ", roleList.Select(n=>n.RoleName.ToString()));
            UserVo.RoleId = string.Join(", ", roleList.Select(n => n.RoleId.ToString()));
            #endregion
            string token = JwtHelper.GenerateJsonWebToken(User);
            var menuList = from u in DataContext.SysUserRoleRelations
                       where u.UserId == User.UserId
                       join i in DataContext.SysRoleMenuAuths on u.RoleId equals i.RoleId
                       join a in DataContext.SysMenuAuthorities on i.MenuAuthId equals a.MenuAuthId
                       select a;
            Dictionary.Add("info", UserVo);//用户信息
            Dictionary.Add("menu", menuList.ToList());//权限菜单
            Dictionary.Add("token", token);//token
            return Dictionary;
        }
    }
}
